import { createRouter, createWebHistory } from 'vue-router'
import Layout from '../views/Layout.vue'
import { useUserStore } from '@/stores/user'

const routes = [
  {
    path: '/',
    component: Layout,
    redirect: '/home',
    children: [
      {
        path: '/home',
        name: 'Home',
        component: () => import('../views/Home/index.vue')
      },
      {
        path: '/room-add',
        name: 'RoomAdd',
        component: () => import('../views/RoomAdd/index.vue')
      },
      {
        path: '/see',
        name: 'See',
        component: () => import('../views/See/index.vue')
      },
      {
        path: '/service',
        name: 'Service',
        component: () => import('../views/Service/index.vue')
      },
      {
        path: '/discover',
        name: 'Discover',
        component: () => import('../views/Discover/index.vue')
      },
      {
        path: '/my',
        name: 'My',
        component: () => import('../views/My/index.vue')
      },
      {
        path: "favorite",
        name: "favorite",
        component: () => import('../views/favorite/index.vue')
      }
    ]
  },
  {
    path: '/auth',
    name: 'Auth',
    component: () => import('../views/Auth/index.vue')
  },
  {
    path: '/room-list',
    name: 'RoomList',
    component: () => import('../views/RoomList/index.vue')
  },
  {
    path: '/booking',
    name: 'Booking',
    component: () => import('../views/Booking/index.vue')
  },
  {
    path: '/rent-room-detail/:id',
    name: 'RentRoomDetail',
    component: () => import('../views/Rentroom/RentRoomDetail.vue')
  },
  {
    path: '/book-info/:roomId',
    name: 'BookInfo',
    component: () => import('../views/Rentroom/BookInfo.vue')
  },
  {
    path: '/service-booking-history',
    name: 'ServiceBookingHistory',
    component: () => import('../views/Service/ServiceBookingHistory.vue')
  },
  {
    path: '/map-test',
    name: 'MapTest',
    component: () => import('../views/MapTest.vue')
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 全局路由守卫，确保用户状态同步
router.beforeEach(async (to, from, next) => {
  const userStore = useUserStore()

  // 如果用户已登录但没有用户信息，尝试刷新
  if (userStore.isLoggedIn && (!userStore.userInfo || !userStore.userInfo.name)) {
    try {
      await userStore.refreshUserInfo()
    } catch (error) {
      console.warn('刷新用户信息失败:', error)
      // 如果刷新失败，清除登录状态
      userStore.userLogout()
    }
  }

  next()
})

export default router
